package cn.zb.config;

import com.alibaba.cloud.commons.io.Charsets;
import com.alibaba.fastjson2.JSON;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 无权限响应配置
 * @Author:
 * @Date: 2024/11/22 18:41
 */

@Component
public class AccessException implements ServerAccessDeniedHandler {


    @Override
    public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) {
        ServerHttpResponse response = exchange.getResponse();
        Map<String,Object> map = new HashMap<>();
        map.put("code",403);
        map.put("msg","无权限访问！！！");
        String s = JSON.toJSONString(map);
        s = new String(s.getBytes(), Charsets.UTF_8);
        DataBuffer db = response.bufferFactory().wrap(s.getBytes());
        // 设置编码
        response.getHeaders().set("content-type","application/json;charset=utf-8");
        return response.writeWith(Mono.just(db));
    }
}